<template>
  <van-nav-bar
    class="search"
    title="登录"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />
  <van-form class="login-form" @submit="onLogin">
    <van-field
      v-model="phone"
      name="手机号"
      label="手机号"
      placeholder="手机号"
      :rules="[{ required: true, message: '请输入手机号' }]"
    />
    <van-field
      v-model="password"
      type="password"
      name="密码"
      label="密码"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="login">
        登 录
      </van-button>
      <van-button
        @click="reg"
        round
        block
        style="margin-top: 15px"
        type="warning"
      >
        注 册
      </van-button>
    </div>
  </van-form>
</template>

<script lang="ts">
import { UserService } from "@/api/user";
import { Notify } from "vant";
import { reactive, toRefs } from "vue";
import { useRouter } from "vue-router";
export default {
  name: "UserLogin",
  setup() {
    const router = useRouter();
    const data = reactive({
      phone: "",
      password: "",
      reg: () => {
        router.push({ path: "/userinfo", query: { title: "注册" } });
      },
    });

    const onClickLeft = () => {
      router.go(-1);
    };
    const onLogin = () => {
      UserService.userlogin(data.phone, data.password).then((res) => {
        if (res.data.code === 0) {
          localStorage.setItem("token", res.data.data);
          router.push({ name: "UserHome" });
        } else {
          Notify({ type: "danger", message: res.data.message });
        }
      });
    };
    return {
      ...toRefs(data),
      onClickLeft,
      onLogin,
    };
  },
};
</script>

<style lang="less" scoped>
.search {
  position: fixed;
  z-index: 999;
  top: 0;
  height: 50px;
  width: 100%;
}
.login-form {
  margin-top: 50px;
}
</style>